<?php
/**
 * @Author:      zk
 * @DateTime:    18-7-21 上午9:50
 * @Description: 审批模型相关
 */
class OAApprovalController extends BaseController{

    public function __construct(){
        header('Access-Control-Allow-Origin:*');	//解决资源跨域问题
	header('Access-Control-Allow-Credentials', 'true');
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-21 上午10:06
     * @Description: 审批类型列表(搜索)
     * @param string $token         用户token
     * @param string $name          搜索名称
     * @param int $page             页码 [默认 1]
     * @param int $page_size        每页显示数据条数 [默认 25]
     * @link: http://api.anhui.com/oa/approval/approvalTypeList?token=1ce108359a4965e9305bd39b8692a1af&page=1&page_size=1&name=请假
     * @return string
     */
    public function approvalTypeList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'page' => 'integer',
                'page_size' => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $name       = Input::get('name', '');               //名称
            $page       = Input::get('page', 1);                //页码 [默认 1]
            $page_size  = Input::get('page_size', 25);          //每页显示数据条数 [默认 25]
            
            $select_arr = [
                'id', 'name', 'status',
            ];
            $list = OAApprovalType::whereIn('status', [1, 2])
                    ->select($select_arr)
                    ->orderBy('id');
            if($name != ''){
                $list->where('name', 'like', '%'.$name.'%');
            }
            $count = $list->count();
            $list = $list->skip($page_size * ($page - 1))->take($page_size)->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('couont' => $count, 'list' => $list));
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalTypeList', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-21 上午10:06
     * @Description: 审批类型 全部数据
     * @param string $token         用户token
     * @link: http://api.anhui.com/oa/approval/approvalTypeAllList?token=1ce108359a4965e9305bd39b8692a1af
     * @return string
     */
    public function approvalTypeAllList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            
            $select_arr = [
                'id', 'name', 
            ];
            $list = OAApprovalType::where('status', 1)
                    ->select($select_arr)
                    ->orderBy('id')
                    ->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('list' => $list));
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalTypeAllList', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-21 上午10:30
     * @Description: 添加、修改审批类型
     * @param string $token         用户token
     * @param string $name          审批类型名称
     * @param int $id               审批类型id
     * @link: http://api.anhui.com/oa/approval/approvalTypeStore?token=1ce108359a4965e9305bd39b8692a1af&name=合同
     * @return  string
     */
    public function approvalTypeStore(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id    = $oa_user->id;                         //管理员id
            $name       = Input::get('name');                   //审批类型名称
            $id         = Input::get('id', '');                 //审批类型id   
            
            //判断审批类型名称是否已经存在
            $exist = OAApprovalType::where('name', $name)
                    ->whereIn('status', [1, 2]);
            if($id != ''){
                $exist->where('id', '!=', $id);
            }
            $exist = $exist->first();
            if($exist){
                $response = Lang::get('oa_error.approval_type_exist_error_221001');
                break;
            }
            if($id != ''){
                $approvalType = OAApprovalType::find($id);
                $old = clone $approvalType;
                $op_old_data = json_encode($old);
                $op_type = 2;   //操作类型 (1:新增;2:修改;3:删除;)
                $op_desc = '编辑审批类型';
                
                $approvalType->updated_at = Common::num2DateTime(time());
                $approvalType->updated_by = $user_id;
                
            } else {
                $approvalType = new OAApprovalType();
                $approvalType->status = 1;
                $approvalType->created_at = Common::num2DateTime(time());
                $approvalType->created_by = $user_id;
                
                $op_type = 1;
                $op_desc = '新增审批类型';
                $op_old_data = '';
            }
            $approvalType->name = $name;
            
            try {
                $approvalType->save();
                // 添加操作日志     start
                $op_model = 'approval/approvalTypeStore';
                $op_new_data = json_encode(OAApprovalType::find($approvalType->id));
                $op_user_id = $user_id;
                OAOpLog::writeLog($op_model, $op_type, $op_desc, $op_old_data, $op_new_data, $op_user_id);
                // 添加操作日志     end
            }catch (Exception $e){
                Log::error('error', ['system' => 'oa', 'event' => 'approval/approvalTypeStore', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_create_error_221002');
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalTypeStore', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-21 上午10:50
     * @Description: 变更审批类型状态
     * @param string $token         用户token
     * @param int $id               审批类型id
     * @param int $status           状态 (1:正常;2:冻结;3:删除;)
     * @link: http://api.anhui.com/oa/approval/approvalTypeStatus?token=1ce108359a4965e9305bd39b8692a1af&id=1&status=3
     * @return  string
     */
    public function approvalTypeStatus(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'status' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id    = $oa_user->id;                     //用户id
            $status     = Input::get('status');             //状态 (1:正常;2:冻结;3:删除;)
            $id         = Input::get('id');                 //审批类型id  
            //如果审批类型正在使用中， 则不能冻结和删除
            $select_arr = [
                'id', 'approval_type_id', 'name', 'icon', 'status', 'approval_number_separator', 'desc',
            ];
            $using = OAApprovalModel::where('approval_type_id', $id)
                    ->where('status', 1)
                    ->select($select_arr)
                    ->first();
            if($using){
                $response = Lang::get('oa_error.approval_type_using_error_221008');
                break;
            }
            
            $approvalType = OAApprovalType::find($id);
            $old = clone $approvalType;
            $op_old_data = json_encode($old);
            try {
                $approvalType->status = $status;
                $approvalType->updated_at = Common::num2DateTime(time());
                $approvalType->updated_by = $user_id;
                $approvalType->save();
                
                // 添加操作日志     start
                $op_type = 2;   //操作类型 (1:新增;2:修改;3:删除;)
                $op_desc = '修改审批类型状态';
                $op_model = 'approval/approvalTypeStatus';
                $op_new_data = json_encode(OAApprovalType::find($approvalType->id));
                $op_user_id = $user_id;
                OAOpLog::writeLog($op_model, $op_type, $op_desc, $op_old_data, $op_new_data, $op_user_id);
                // 添加操作日志     end
            }catch (Exception $e){
                Log::error('error', ['system' => 'oa', 'event' => 'approval/approvalTypeStatus', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_update_status_error_221003');
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalTypeStatus', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-21 上午10:58
     * @Description: 审批类型详情
     * @param string $token         用户token
     * @param int $id               审批类型id
     * @link: http://api.anhui.com/oa/approval/approvalTypeDetails?token=cbaeef3465cf329e7167fedb847fb11b&id=1
     * @return  string
     */
    public function approvalTypeDetails(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $id         = Input::get('id');                 //审批类型id
            $select_arr = [
                'id', 'name', 'status',
            ];
            $info = OAApprovalType::where('id', $id)->select($select_arr)->first();
            
            $response = array('code' => 0, 'msg' => 'ok','result' => ['info' => $info]);
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalTypeDetails', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-23 上午11:10
     * @Description: 添加审批模型
     * @param string    $token                          用户token
     * @param int       $approval_type_id               审批类型id
     * @param string    $name                           模型名称
     * @param string    $icon                           模型图标名称
     * @param string    $number_rule                    审批编号规则
     * 规则说明如下
     * $number_rule = [
                [
                    'type' => 1,    //类型 (1:标签;2:日期;3:增长值;)
                    'sort' => 1,    //排序
                    'tag_name' => 'AH',    //标签名称
                    'date_type' => 0,    //日期类型(1:YYYY;2:YYYYmm;3:YYYY-mm;4:YYYYmmdd;5:YYYY-mm-dd;)
                    'add_value' => 0,    //增长初始值
                    'add_places' => 0,    //增长值位数
                ],
                [
                    'type' => 2,    //类型 (1:标签;2:日期;3:增长值;)
                    'sort' => 2,    //排序
                    'tag_name' => '',    //标签名称
                    'date_type' => 4,    //日期类型(1:YYYY;2:YYYYmm;3:YYYY-mm;4:YYYYmmdd;5:YYYY-mm-dd;)
                    'add_value' => 0,    //增长初始值
                    'add_places' => 0,    //增长值位数
                ],
                [
                    'type' => 3,    //类型 (1:标签;2:日期;3:增长值;)
                    'sort' => 3,    //排序
                    'tag_name' => '',    //标签名称
                    'date_type' => 0,    //日期类型(1:YYYY;2:YYYYmm;3:YYYY-mm;4:YYYYmmdd;5:YYYY-mm-dd;)
                    'add_value' => 1,    //增长初始值
                    'add_places' => 4,    //增长值位数
                ],
            ]; 
     * 例如 ： [{"type":1,"sort":1,"tag_name":"AH","date_type":0,"add_value":0,"add_places":0},{"type":2,"sort":2,"tag_name":"","date_type":4,"add_value":0,"add_places":0},{"type":3,"sort":3,"tag_name":"","date_type":0,"add_value":1,"add_places":4}]
     * @param string    $approval_number_separator      审批编号分隔符(用来分隔'审批编号配置表')
     * @param string    $desc                           审批说明描述
     * @param string    $form_set                       表单设置(json存储有顺序规则)
     * 规则说明
     *  $test = [
            [
                //所有数值型的不填，则填写0
                'widget_type' => 1, //控件类型 (1:单行文本;2:多行文本;3:数字;4:金额;5:日期;6:日期区间;7:单选框;8:多选框;9:下拉菜单;10:文本;11:附件;)
                'widget_title' => '申请人', //控件标题 (如果不需要则为空)
                'widget_prompt' => '谁提交的申请', //控件的提示说明 (如果不需要则为空)
                'widget_required' => 1,    //是否必填 (1:必填;2:不必填;)
                'widget_unit' => '天', //控件单位 (如果不需要则为空)
                'widget_date_format' => 2, //时间格式 (1:YYYY-mm-dd HH:ii;2:YYYY-mm-dd;3:YYYY-mm;4:HH:ii;)    
                'widget_option' => '', //选择项 多个值用竖线分隔 ','    (如果不需要则为空)
                'widget_sort' => 1, //控件排序
                'widget_ext_id' => 'apply_id', //前端自定义id    (可以作为条件名称使用)
            ],
            [
                //所有数值型的不填，则填写0
                'widget_type' => 6, //控件类型 (1:单行文本;2:多行文本;3:数字;4:金额;5:日期;6:日期区间;7:单选框;8:多选框;9:下拉菜单;10:文本;11:附件;)
                'widget_title' => '时间', //控件标题 (如果不需要则为空)
                'widget_prompt' => '请假时间', //控件的提示说明 (如果不需要则为空)
                'widget_required' => 1,    //是否必填 (1:必填;2:不必填;)
                'widget_unit' => '小时', //控件单位 (如果不需要则为空)    
                'widget_date_format' => 1, //时间格式 (1:YYYY-mm-dd HH:ii;2:YYYY-mm-dd;3:YYYY-mm;4:HH:ii;)    
                'widget_option' => '', //选择项 多个值用竖线分隔 ','    (如果不需要则为空)
                'widget_sort' => 2, //控件排序
                'widget_ext_id' => 'time_id', //前端自定义id    (可以作为条件名称使用)
            ],
        ];
     * 例如 ： [{"widget_type":1,"widget_title":"申请人","widget_prompt":"谁提交的申请","widget_required":1,"widget_unit":"天","widget_date_format":2,"widget_option":"","widget_sort":1,"widget_ext_id":"apply_id"},{"widget_type":6,"widget_title":"时间","widget_prompt":"请假时间","widget_required":1,"widget_unit":"小时","widget_date_format":1,"widget_option":"","widget_sort":2,"widget_ext_id":"time_id"}]
     * @param int       $pc                             pc端消息展示状态(1:显示;2:不显示;)
     * @param int       $wechat                         微站端消息展示状态(1:显示;2:不显示;)
     * @param int       $email                          emali消息通知状态(1:通知;2:不通知;)
     * @param string    $approver                       审批人    json串
     * 规则说明
     *  $approver = [
                [
                    'level' => 1,   //审批等级
                    'role_ids' => [],   //角色的id数组 如果为空则为空数组
                    'user_ids' => [1],   //用户id数组 如果为空则为空数组
                    'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                    'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                    //下一级
                    'children' => [
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [3],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'children' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ],
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [5],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'children' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ], 
                    ],
                    //审批条件
                    'condition' => [
                        [
                            'key_name' => '天数',   //条件名称(表单里设置的)
                            'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                            'key_value' => '3',   //条件值(多个英文逗号分隔)
                            'sort' => 1,    //条件排序
                            'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                        ]
                    ]
                ],
                [
                    'level' => 1,   //审批等级
                    'role_ids' => [],   //角色的id数组 如果为空则为空数组
                    'user_ids' => [2],   //用户id数组 如果为空则为空数组
                    'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                    'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                    //下一级
                    'children' => [
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [3],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'children' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ],
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [5],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'next' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ], 
                    ],
                    //审批条件
                    'condition' => [
                        [
                            'key_name' => '天数',   //条件名称(表单里设置的)
                            'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                            'key_value' => '3',   //条件值(多个英文逗号分隔)
                            'sort' => 1,    //条件排序
                            'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                        ]
                    ]
                ]
            ];
     * 例如     [{"level":1,"role_ids":[],"user_ids":[1],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[{"level":2,"role_ids":[1],"user_ids":[3],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]},{"level":2,"role_ids":[1],"user_ids":[5],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]}],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]},{"level":1,"role_ids":[],"user_ids":[2],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[{"level":2,"role_ids":[1],"user_ids":[3],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]},{"level":2,"role_ids":[1],"user_ids":[5],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]}],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]}]
     * @param string    $use_user_id                    使用人员  json 串 
     * 规则说明 
     *      (type 类型 1:全部用户;2:部分用户; hrm_users: htm用户id数组)
     * $test = [
            'type' => 2,
            'hrm_users' => [1,2,3]
        ];
     * 例如     {"type":2,"hrm_users":[1,2,3]}  
     * @param string    $copy_user_id                   抄送人员  json 串 [1,2,3]  htm用户id数组
     * 规则说明
     *      htm用户id数组json串
     * 例如     [1,2,3]
     * @link: http://api.anhui.com/oa/approval/approvalModelAdd?token=19fc512f10945dd707c0629ff3f47899
     * @return string
     */
    public function approvalModelAdd(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'approval_type_id' => 'required',
                'name' => 'required',
                'number_rule' => 'required',
                'form_set' => 'required',
                'approver' => 'required',
                'use_user_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            
            $approval_type_id           = Input::get('approval_type_id');           //审批类型id
            $name                       = Input::get('name');                       //模型名称
            $icon                       = Input::get('icon', '');                   //模型图标名称
            $number_rule                = Input::get('number_rule');                //审批编号规则
            $approval_number_separator  = Input::get('approval_number_separator', '');  //审批编号分隔符(用来分隔'审批编号配置表')
            $desc                       = Input::get('desc', '');                   //审批说明
            $form_set                   = Input::get('form_set');                   //表单设置(json存储有顺序规则)
            $pc                         = Input::get('pc', 0);                      //pc端消息展示状态(1:显示;2:不显示;)
            $wechat                     = Input::get('wechat', 0);                  //微站端消息展示状态(1:显示;2:不显示;)
            $email                      = Input::get('email', 0);                   //emali消息通知状态(1:通知;2:不通知;)
            $approver                   = Input::get('approver');                   //审批人    json串
            $use_user_id                = Input::get('use_user_id');                //使用人员  json 串 {"type":2,"hrm_users":[1,2,3]}  (type 类型 1:全部用户;2:部分用户; users: htm用户id数组)
            $copy_user_id               = Input::get('copy_user_id', '');           //抄送人员  json 串 [1,2,3]  htm用户id数组

            $number_rule_arr = json_decode($number_rule, TRUE);     //审批编号规则 数组
            if(empty($number_rule_arr)){
                $response = Lang::get('oa_error.approval_args_error_221005');
                break;
            }
            $using_arr = json_decode($use_user_id, TRUE);     //使用人员数组
            $use_user_id_arr = [];  //使用人员数组
            if(isset($using_arr['type']) && $using_arr['type'] == 2){
                //部分用户
                if(!isset($using_arr['hrm_users']) || empty($using_arr['hrm_users'])){
                    $response = Lang::get('oa_error.approval_args_error_221006');
                    break;
                }
                $use_user_id_arr = OAUser::getUseridByHrmUserid($using_arr['hrm_users']);    //hrm用户id转换成OA用户id
            } elseif (!isset($using_arr['type']) || $using_arr['type'] != 1) {
                //全部用户
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            if($copy_user_id != ''){
                $copy_user_id_arr = json_decode($copy_user_id, TRUE);   //抄送人员数组
                if(empty($copy_user_id_arr)){
                    $response = Lang::get('oa_error.approval_args_error_221007');
                    break;
                }
                $copy_user_id_arr = OAUser::getUseridByHrmUserid($copy_user_id_arr);    //hrm用户id转换成OA用户id
            } else {
                $copy_user_id_arr = [];
            }
            $approver_arr = json_decode($approver, TRUE);   //审批人参数数组
            if(empty($approver_arr)){
                $response = Lang::get('oa_error.approval_args_error_221009');
                break;
            }

            // 开始添加 审批模板相关数据 ……
            $approvalModel = new OAApprovalModel();
            $approvalModel->status = 1;
            $approvalModel->lock_status = 1;
            $approvalModel->created_at = Common::num2DateTime(time());
            $approvalModel->created_by = $user_id;
            $approvalModel->approval_type_id = $approval_type_id;           //审批类型id
            $approvalModel->name = $name;                                   //模型名称
            if($icon != ''){
                $approvalModel->icon = $icon;                               //模型图标名称
            }
            if($approval_number_separator != ''){
                $approvalModel->approval_number_separator = $approval_number_separator;  //审批编号分隔符(用来分隔'审批编号配置表')
            }
            if($desc != ''){
                $approvalModel->desc = $desc;                               //审批说明
            }
            $approvalModel->form_set = $form_set;                           //表单设置(json存储有顺序规则)
            $approvalModel->pc = $pc;                                       //pc端消息展示状态(1:显示;2:不显示;)
            if($wechat != ''){
                $approvalModel->wechat = $wechat;                           //微站端消息展示状态(1:显示;2:不显示;)
            }
            if($email != ''){
                $approvalModel->email = $email;                             //emali消息通知状态(1:通知;2:不通知;)
            }
            
            DB::beginTransaction();
            try{
                $res_am = $approvalModel->save();
                if(!$res_am){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_model_create_error_221004');
                    break;
                }

                $LogErrorInfo = OAOpLog::writeLog('approval/approvalModelAdd', 1, '添加审批模型', '', json_encode($res_am), $user_id);
                if (!$LogErrorInfo) {
                    DB::rollBack();
                    $response = Lang::get('oa_error.new_log_write_error_212001');
                    break;
                }
                
                //审批编号规则  处理 start……
                $insert_data_number_rule = [];      //审批编号规则待添加数据
                $approval_model_id = $approvalModel->id;             //审批模板id
                foreach ($number_rule_arr as $k => $v) {
                    $temp = [
                        'approval_model_id' => $approval_model_id,
                        'sort' => $v['sort'],
                        'type' => $v['type'],
                        'tag_name' => $v['tag_name'],
                        'date_type' => $v['date_type'],
                        'add_value' => $v['add_value'],
                        'add_places' => $v['add_places'],
                        'status' => 1,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_data_number_rule[] = $temp;
                }
                $ins_number_rule = OAApprovalNumberRuleConfig::insert($insert_data_number_rule);
                if(!$ins_number_rule){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_args_error_221015');
                    break;
                }
                //审批编号规则  处理 end……
                
                //添加 审批模型的使用人员 start……
                $insert_data_user = [];      //审批模型的使用人员添加数据
                if($using_arr['type'] == 1){
                    $temp = [
                        'approval_model_id' => $approval_model_id,
                        'type' => $using_arr['type'],    //类型 1:全部用户;2:部分用户;
                        'status' => 1,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_data_user[] = $temp;
                } elseif ($using_arr['type'] == 2) {
                    if(!empty($use_user_id_arr)){   //转换后的OA用户
                        foreach ($use_user_id_arr as $k => $v) {
                            $temp = [
                                'approval_model_id' => $approval_model_id,
                                'type' => $using_arr['type'],    //类型 1:全部用户;2:部分用户;
                                'user_id' => $v,
                                'status' => 1,
                                'created_by' => $user_id,
                                'created_at' => Common::num2DateTime(time()),
                            ];
                            $insert_data_user[] = $temp;
                        }    
                    }
                }
                $ins_user = OAApprovalModelApplyConfig::insert($insert_data_user);
                if(!$ins_user){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_args_error_221014');
                    break;
                }
                //添加 审批模型的使用人员 end……
                
                //添加 审批模型的抄送人员 start……
                if(!empty($copy_user_id_arr)){
                    $insert_data_copy_user = [];      //审批模型的抄送人员添加数据
                    //getUserByHrmUserid
                    foreach ($copy_user_id_arr as $k => $v) {
                        $temp = [
                            'approval_model_id' => $approval_model_id,
                            'type' => 1,    //类型 1:用户;2:角色;
                            'user_type' => 2,   //用户类型 1:审批人员;2:抄送人员;
                            'user_id' => $v,
                            'status' => 1,
                            'created_by' => $user_id,
                            'created_at' => Common::num2DateTime(time()),
                        ];
                        $insert_data_copy_user[] = $temp;
                    }
                    $ins_copy_user = OAApproverConfig::insert($insert_data_copy_user);
                    if(!$ins_copy_user){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_args_error_221013');
                        break;
                    }
                }
                //添加 审批模型的抄送人员 end……
                
                //添加审批人、审批条件 start……
                $res_insert_approver = OAApproverRuleGroup::addApprover($approval_model_id, $user_id, $approver_arr, 0);
                if(!$res_insert_approver){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_args_error_221010');
                    break;
                }
                //添加审批人、审批条件 end……
            
                DB::commit();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => ['id' => $approval_model_id]);
            } catch (\Exception $e){
                DB::rollback();
                Log::error('error', ['system' => 'oa', 'event' => 'approval/approvalModelAdd', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_model_create_error_221004');
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalModelAdd', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-26 下午2:15
     * @Description: 修改编辑审批模型   【 编辑的时候如果该模板已经被使用，则重新新增 】
     * @param string    $token                          用户token
     * @param int       $id                             审批模型id
     * @param int       $approval_type_id               审批类型id
     * @param string    $name                           模型名称
     * @param string    $icon                           模型图标名称
     * @param string    $number_rule                    审批编号规则
     * 规则说明如下
     * $number_rule = [
                [
                    'type' => 1,    //类型 (1:标签;2:日期;3:增长值;)
                    'sort' => 1,    //排序
                    'tag_name' => 'AH',    //标签名称
                    'date_type' => 0,    //日期类型(1:YYYY;2:YYYYmm;3:YYYY-mm;4:YYYYmmdd;5:YYYY-mm-dd;)
                    'add_value' => 0,    //增长初始值
                    'add_places' => 0,    //增长值位数
                ],
                [
                    'type' => 2,    //类型 (1:标签;2:日期;3:增长值;)
                    'sort' => 2,    //排序
                    'tag_name' => '',    //标签名称
                    'date_type' => 4,    //日期类型(1:YYYY;2:YYYYmm;3:YYYY-mm;4:YYYYmmdd;5:YYYY-mm-dd;)
                    'add_value' => 0,    //增长初始值
                    'add_places' => 0,    //增长值位数
                ],
                [
                    'type' => 3,    //类型 (1:标签;2:日期;3:增长值;)
                    'sort' => 3,    //排序
                    'tag_name' => '',    //标签名称
                    'date_type' => 0,    //日期类型(1:YYYY;2:YYYYmm;3:YYYY-mm;4:YYYYmmdd;5:YYYY-mm-dd;)
                    'add_value' => 1,    //增长初始值
                    'add_places' => 4,    //增长值位数
                ],
            ]; 
     * 例如 ： [{"type":1,"sort":1,"tag_name":"AH","date_type":0,"add_value":0,"add_places":0},{"type":2,"sort":2,"tag_name":"","date_type":4,"add_value":0,"add_places":0},{"type":3,"sort":3,"tag_name":"","date_type":0,"add_value":1,"add_places":4}]
     * @param string    $approval_number_separator      审批编号分隔符(用来分隔'审批编号配置表')
     * @param string    $desc                           审批说明描述
     * @param string    $form_set                       表单设置(json存储有顺序规则)
     * 规则说明
     *  $test = [
            [
                //所有数值型的不填，则填写0
                'widget_type' => 1, //控件类型 (1:单行文本;2:多行文本;3:数字;4:金额;5:日期;6:日期区间;7:单选框;8:多选框;9:下拉菜单;10:文本;11:附件;)
                'widget_title' => '申请人', //控件标题 (如果不需要则为空)
                'widget_prompt' => '谁提交的申请', //控件的提示说明 (如果不需要则为空)
                'widget_required' => 1,    //是否必填 (1:必填;2:不必填;)
                'widget_unit' => '天', //控件单位 (如果不需要则为空)
                'widget_date_format' => 2, //时间格式 (1:YYYY-mm-dd HH:ii;2:YYYY-mm-dd;3:YYYY-mm;4:HH:ii;)    
                'widget_option' => '', //选择项 多个值用竖线分隔 ','    (如果不需要则为空)
                'widget_sort' => 1, //控件排序
                'widget_ext_id' => 'apply_id', //前端自定义id    (可以作为条件名称使用)
            ],
            [
                //所有数值型的不填，则填写0
                'widget_type' => 6, //控件类型 (1:单行文本;2:多行文本;3:数字;4:金额;5:日期;6:日期区间;7:单选框;8:多选框;9:下拉菜单;10:文本;11:附件;)
                'widget_title' => '时间', //控件标题 (如果不需要则为空)
                'widget_prompt' => '请假时间', //控件的提示说明 (如果不需要则为空)
                'widget_required' => 1,    //是否必填 (1:必填;2:不必填;)
                'widget_unit' => '小时', //控件单位 (如果不需要则为空)    
                'widget_date_format' => 1, //时间格式 (1:YYYY-mm-dd HH:ii;2:YYYY-mm-dd;3:YYYY-mm;4:HH:ii;)    
                'widget_option' => '', //选择项 多个值用竖线分隔 ','    (如果不需要则为空)
                'widget_sort' => 2, //控件排序
                'widget_ext_id' => 'time_id', //前端自定义id    (可以作为条件名称使用)
            ],
        ];
     * 例如 ： [{"widget_type":1,"widget_title":"申请人","widget_prompt":"谁提交的申请","widget_required":1,"widget_unit":"天","widget_date_format":2,"widget_option":"","widget_sort":1,"widget_ext_id":"apply_id"},{"widget_type":6,"widget_title":"时间","widget_prompt":"请假时间","widget_required":1,"widget_unit":"小时","widget_date_format":1,"widget_option":"","widget_sort":2,"widget_ext_id":"time_id"}]
     * @param int       $pc                             pc端消息展示状态(1:显示;2:不显示;)
     * @param int       $wechat                         微站端消息展示状态(1:显示;2:不显示;)
     * @param int       $email                          emali消息通知状态(1:通知;2:不通知;)
     * @param string    $approver                       审批人    json串
     * 规则说明
     *  $approver = [
                [
                    'level' => 1,   //审批等级
                    'role_ids' => [],   //角色的id数组 如果为空则为空数组
                    'user_ids' => [1],   //用户id数组 如果为空则为空数组
                    'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                    'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                    'name' => '前端自定义name值',    //审批人字符串(前端自定义name值)
                    //下一级
                    'children' => [
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [3],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'name' => '前端自定义name值',    //审批人字符串(前端自定义name值)
                            'children' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ],
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [5],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'name' => '前端自定义name值',    //审批人字符串(前端自定义name值)
                            'children' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ], 
                    ],
                    //审批条件
                    'condition' => [
                        [
                            'key_name' => '天数',   //条件名称(表单里设置的)
                            'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                            'key_value' => '3',   //条件值(多个英文逗号分隔)
                            'sort' => 1,    //条件排序
                            'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                        ]
                    ]
                ],
                [
                    'level' => 1,   //审批等级
                    'role_ids' => [],   //角色的id数组 如果为空则为空数组
                    'user_ids' => [2],   //用户id数组 如果为空则为空数组
                    'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                    'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                    'name' => '前端自定义name值',    //审批人字符串(前端自定义name值)
                    //下一级
                    'children' => [
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [3],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'name' => '前端自定义name值',    //审批人字符串(前端自定义name值)
                            'children' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ],
                        [
                            'level' => 2,   //审批等级
                            'role_ids' => [1],   //角色的id数组 如果为空则为空数组
                            'user_ids' => [5],   //用户id数组 如果为空则为空数组
                            'user_type' => 2,   //用户id类型 [1:OA用户id;2:hrm平台用户id;]  选择角色时,该值为0
                            'approval_way' => 1,    //审批方式 (1:单人审批;2:会签;3:或签;)
                            'name' => '前端自定义name值',    //审批人字符串(前端自定义name值)
                            'children' => [
                                
                            ],
                            //审批条件
                            'condition' => [
                                [
                                    'key_name' => '天数',   //条件名称(表单里设置的)
                                    'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                                    'key_value' => '3',   //条件值(多个英文逗号分隔)
                                    'sort' => 1,    //条件排序
                                    'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                                ]
                            ]
                        ], 
                    ],
                    //审批条件
                    'condition' => [
                        [
                            'key_name' => '天数',   //条件名称(表单里设置的)
                            'operator' => '4',   //条件运算符(多个英文逗号分隔)[1:=;2:!=;3:<;4:>;5:<=;6:>=;7:in;]
                            'key_value' => '3',   //条件值(多个英文逗号分隔)
                            'sort' => 1,    //条件排序
                            'relation' => 1,    //关系 (与下一条件关系 1:and;2:or;)
                        ]
                    ]
                ]
            ];
     * 例如    [{"level":1,"role_ids":[],"user_ids":[1],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[{"level":2,"role_ids":[1],"user_ids":[3],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]},{"level":2,"role_ids":[1],"user_ids":[5],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]}],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]},{"level":1,"role_ids":[],"user_ids":[2],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[{"level":2,"role_ids":[1],"user_ids":[3],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]},{"level":2,"role_ids":[1],"user_ids":[5],"user_type":2,"approval_way":1,"name":"\u524d\u7aef\u81ea\u5b9a\u4e49name\u503c","children":[],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]}],"condition":[{"key_name":"\u5929\u6570","operator":"4","key_value":"3","sort":1,"relation":1}]}]
     * @param string    $use_user_id                    使用人员  json 串 
     * 规则说明 
     *      (type 类型 1:全部用户;2:部分用户; hrm_users: htm用户id数组)
     * $test = [
            'type' => 2,
            'hrm_users' => [1,2,3]
        ];
     * 例如     {"type":2,"hrm_users":[1,2,3]}  
     * @param string    $copy_user_id                   抄送人员  json 串 [1,2,3]  htm用户id数组
     * 规则说明
     *      htm用户id数组json串
     * 例如     [1,2,3]
     * 
     * @link: http://api.anhui.com/oa/approval/approvalModelModify?token=19fc512f10945dd707c0629ff3f47899
     * @link: http://api.anhui.com/oa/approval/approvalModelModify?id=2&token=b6a92158c775fc80e6e3f5d438bf4811&approval_type_id=3&name=%E8%AF%B7%E5%81%87%E7%94%B3%E8%AF%B7&icon=test.png&number_rule=[{%22type%22:1,%22sort%22:1,%22tag_name%22:%22AH%22,%22date_type%22:0,%22add_value%22:0,%22add_places%22:0},{%22type%22:2,%22sort%22:2,%22tag_name%22:%22%22,%22date_type%22:4,%22add_value%22:0,%22add_places%22:0},{%22type%22:3,%22sort%22:3,%22tag_name%22:%22%22,%22date_type%22:0,%22add_value%22:1,%22add_places%22:4}]&approval_number_separator=*&desc=%E8%AF%B7%E5%81%87%E7%94%B3%E8%AF%B7&form_set=[{%22widget_type%22:7,%22widget_title%22:%22\u8bf7\u5047\u7c7b\u578b%22,%22widget_prompt%22:%22\u8bf7\u5047\u7684\u7533\u8bf7%22,%22widget_required%22:1,%22widget_unit%22:%22%22,%22widget_date_format%22:0,%22widget_option%22:%22\u4e8b\u5047|\u5e74\u5047|\u75c5\u5047%22,%22widget_sort%22:1,%22widget_ext_id%22:%22qingjiadeleixing_1%22},{%22widget_type%22:1,%22widget_title%22:%22\u5929\u6570%22,%22widget_prompt%22:%22\u8bf7\u5047\u7684\u5929\u6570%22,%22widget_required%22:1,%22widget_unit%22:%22\u5929%22,%22widget_date_format%22:2,%22widget_option%22:%22%22,%22widget_sort%22:2,%22widget_ext_id%22:%22tianshu_2%22},{%22widget_type%22:1,%22widget_title%22:%22\u4e8b\u7531%22,%22widget_prompt%22:%22\u8bf7\u5047\u7684\u7406\u7531%22,%22widget_required%22:1,%22widget_unit%22:%22%22,%22widget_date_format%22:0,%22widget_option%22:%22%22,%22widget_sort%22:3,%22widget_ext_id%22:%22liyou_3%22}]&pc=1&approver=[{%22level%22:1,%22role_ids%22:[],%22user_ids%22:[1],%22user_type%22:2,%22approval_way%22:1,%22next%22:[{%22level%22:2,%22role_ids%22:[1],%22user_ids%22:[3],%22user_type%22:2,%22approval_way%22:1,%22next%22:[],%22condition%22:[{%22key_name%22:%22\u5929\u6570%22,%22operator%22:%224%22,%22key_value%22:%223%22,%22sort%22:1,%22relation%22:1}]},{%22level%22:2,%22role_ids%22:[1],%22user_ids%22:[5],%22user_type%22:2,%22approval_way%22:1,%22next%22:[],%22condition%22:[{%22key_name%22:%22\u5929\u6570%22,%22operator%22:%224%22,%22key_value%22:%223%22,%22sort%22:1,%22relation%22:1}]}],%22condition%22:[{%22key_name%22:%22\u5929\u6570%22,%22operator%22:%224%22,%22key_value%22:%223%22,%22sort%22:1,%22relation%22:1}]},{%22level%22:1,%22role_ids%22:[],%22user_ids%22:[2],%22user_type%22:2,%22approval_way%22:1,%22next%22:[{%22level%22:2,%22role_ids%22:[1],%22user_ids%22:[3],%22user_type%22:2,%22approval_way%22:1,%22next%22:[],%22condition%22:[{%22key_name%22:%22\u5929\u6570%22,%22operator%22:%224%22,%22key_value%22:%223%22,%22sort%22:1,%22relation%22:1}]},{%22level%22:2,%22role_ids%22:[1],%22user_ids%22:[5],%22user_type%22:2,%22approval_way%22:1,%22next%22:[],%22condition%22:[{%22key_name%22:%22\u5929\u6570%22,%22operator%22:%224%22,%22key_value%22:%223%22,%22sort%22:1,%22relation%22:1}]}],%22condition%22:[{%22key_name%22:%22\u5929\u6570%22,%22operator%22:%224%22,%22key_value%22:%223%22,%22sort%22:1,%22relation%22:1}]}]&use_user_id={%22type%22:1,%22hrm_users%22:[]}&copy_user_id=[1,2,3]
     * @return  string
     */
    public function approvalModelModify(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'approval_type_id' => 'required',
                'name' => 'required',
                'number_rule' => 'required',
                'form_set' => 'required',
                'approver' => 'required',
                'use_user_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            
            $id                         = Input::get('id');                         //审批模板id
            $approval_type_id           = Input::get('approval_type_id');           //审批类型id
            $name                       = Input::get('name');                       //模型名称
            $icon                       = Input::get('icon', '');                   //模型图标名称
            $approval_number_separator  = Input::get('approval_number_separator', '');  //审批编号分隔符(用来分隔'审批编号配置表')
            $desc                       = Input::get('desc', '');                   //审批说明
            $form_set                   = Input::get('form_set');                   //表单设置(json存储有顺序规则)
            $pc                         = Input::get('pc', 0);                      //pc端消息展示状态(1:显示;2:不显示;)
            $wechat                     = Input::get('wechat', 0);                  //微站端消息展示状态(1:显示;2:不显示;)
            $email                      = Input::get('email', 0);                   //emali消息通知状态(1:通知;2:不通知;)
            $approver                   = Input::get('approver');                   //审批人    json串
            $use_user_id                = Input::get('use_user_id');                //使用人员  json 串 {"type":2,"hrm_users":[1,2,3]}  (type 类型 1:全部用户;2:部分用户; users: htm用户id数组)
            $copy_user_id               = Input::get('copy_user_id', '');           //抄送人员  json 串 [1,2,3]  htm用户id数组
            $number_rule                = Input::get('number_rule');                //审批编号规则
            
            $number_rule_arr = json_decode($number_rule, TRUE);     //审批编号规则 数组
            if(empty($number_rule_arr)){
                $response = Lang::get('oa_error.approval_args_error_221005');
                break;
            }
            $using_arr = json_decode($use_user_id, TRUE);     //使用人员数组
            $use_user_id_arr = [];  //使用人员数组
            if(isset($using_arr['type']) && $using_arr['type'] == 2){
                //部分用户
                if(!isset($using_arr['hrm_users']) || empty($using_arr['hrm_users'])){
                    $response = Lang::get('oa_error.approval_args_error_221006');
                    break;
                }
                $use_user_id_arr = OAUser::getUseridByHrmUserid($using_arr['hrm_users']);    //hrm用户id转换成OA用户id
            } elseif (!isset($using_arr['type']) || $using_arr['type'] != 1) {
                //全部用户
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            if($copy_user_id != ''){
                $copy_user_id_arr = json_decode($copy_user_id, TRUE);   //抄送人员数组
                if(empty($copy_user_id_arr)){
                    $response = Lang::get('oa_error.approval_args_error_221007');
                    break;
                }
                $copy_user_id_arr = OAUser::getUseridByHrmUserid($copy_user_id_arr);    //hrm用户id转换成OA用户id
            } else {
                $copy_user_id_arr = [];
            }
            $approver_arr = json_decode($approver, TRUE);   //审批人参数数组
            if(empty($approver_arr)){
                $response = Lang::get('oa_error.approval_args_error_221009');
                break;
            }

            //查看锁定状态
            $lock_status = OAApprovalModel::getLockStatus($id);
            if($lock_status){
                $response = Lang::get('oa_error.approval_model_lock_error_221025');
                break;
            }
            //校验 审批模板的 历史使用情况
            $use_tag = OAApprovalModel::getApprovalModelUsingHistory($id);
            if($use_tag){
                //已被使用  则新建
                $oldApprovalModel = OAApprovalModel::find($id);    //原审批模板
                
                $approvalModel = new OAApprovalModel();
                $approvalModel->created_at = Common::num2DateTime(time());
                $approvalModel->created_by = $user_id;
                $approvalModel->status = 1;
                $oldData = '';
                $LogType = 1;
                $LogDesc = '新建审批模型';
            } else {
                //未使用    则编辑
                $approvalModel = OAApprovalModel::find($id);
                $oldData = json_encode($approvalModel);
                $LogType = 2;
                $LogDesc = '修改审批模型';
                $approvalModel->updated_at = Common::num2DateTime(time());
                $approvalModel->updated_by = $user_id;
            }
            
            // 开始添加 审批模板相关数据 ……
            $approvalModel->approval_type_id = $approval_type_id;           //审批类型id
            $approvalModel->name = $name;                                   //模型名称
            if($icon != ''){
                $approvalModel->icon = $icon;                               //模型图标名称
            }
            if($approval_number_separator != ''){
                $approvalModel->approval_number_separator = $approval_number_separator;  //审批编号分隔符(用来分隔'审批编号配置表')
            }
            if($desc != ''){
                $approvalModel->desc = $desc;                               //审批说明
            }
            $approvalModel->form_set = $form_set;                           //表单设置(json存储有顺序规则)
            $approvalModel->pc = $pc;                                       //pc端消息展示状态(1:显示;2:不显示;)
            if($wechat != ''){
                $approvalModel->wechat = $wechat;                           //微站端消息展示状态(1:显示;2:不显示;)
            }
            if($email != ''){
                $approvalModel->email = $email;                             //emali消息通知状态(1:通知;2:不通知;)
            }
            
            DB::beginTransaction();
            try{
                $res_am = $approvalModel->save();
                if(!$res_am){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_model_create_error_221004');
                    break;
                }

                $LogErrorInfo = OAOpLog::writeLog('approval/approvalModelModify', $LogType, $LogDesc, $oldData, json_encode($res_am), $user_id);
                if (!$LogErrorInfo) {
                    DB::rollBack();
                    $response = Lang::get('oa_error.new_log_write_error_212001');
                    break;
                }
                //审批编号规则  处理 start……
                if(!$use_tag){   //未被使用 审批编号规则先删除再创建
                    $update_data = [
                        'status' => 2,
                        'updated_at' => Common::num2DateTime(time()),
                        'updated_by' => $user_id,
                    ];
                    $update_res = OAApprovalNumberRuleConfig::where('approval_model_id', $id)
                            ->update($update_data);
                    if(!$update_res){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_update_args_error_221017');
                        break;
                    }
                }
                
                $insert_data_number_rule = [];      //审批编号规则待添加数据
                $approval_model_id = $approvalModel->id;             //审批模板id
                foreach ($number_rule_arr as $k => $v) {
                    $temp = [
                        'approval_model_id' => $approval_model_id,
                        'sort' => $v['sort'],
                        'type' => $v['type'],
                        'tag_name' => $v['tag_name'],
                        'date_type' => $v['date_type'],
                        'add_value' => $v['add_value'],
                        'add_places' => $v['add_places'],
                        'status' => 1,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_data_number_rule[] = $temp;
                }
                $ins_number_rule = OAApprovalNumberRuleConfig::insert($insert_data_number_rule);
                if(!$ins_number_rule){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_args_error_221015');
                    break;
                }
                //审批编号规则  处理 end……
                
                //添加 审批模型的使用人员 start……
                if(!$use_tag){   //未被使用 审批模型的使用人员先删除再创建
                    $update_data = [
                        'status' => 2,
                        'updated_at' => Common::num2DateTime(time()),
                        'updated_by' => $user_id,
                    ];
                    $update_res = OAApprovalModelApplyConfig::where('approval_model_id', $id)
                            ->update($update_data);
                    if(!$update_res){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_update_args_error_221018');
                        break;
                    }
                }
                
                $insert_data_user = [];      //审批模型的使用人员添加数据
                if($using_arr['type'] == 1){
                    $temp = [
                        'approval_model_id' => $approval_model_id,
                        'type' => $using_arr['type'],    //类型 1:全部用户;2:部分用户;
                        'status' => 1,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_data_user[] = $temp;
                } elseif ($using_arr['type'] == 2) {
                    if(!empty($use_user_id_arr)){   //转换后的OA用户
                        foreach ($use_user_id_arr as $k => $v) {
                            $temp = [
                                'approval_model_id' => $approval_model_id,
                                'type' => $using_arr['type'],    //类型 1:全部用户;2:部分用户;
                                'user_id' => $v,
                                'status' => 1,
                                'created_by' => $user_id,
                                'created_at' => Common::num2DateTime(time()),
                            ];
                            $insert_data_user[] = $temp;
                        }    
                    }
                }
                $ins_user = OAApprovalModelApplyConfig::insert($insert_data_user);
                if(!$ins_user){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_args_error_221014');
                    break;
                }
                //添加 审批模型的使用人员 end……
                
                //添加 审批模型的抄送人员 start……
                if(!$use_tag){   //未被使用 审批模型的抄送人员先删除再创建
                    //user_type  用户类型 1:审批人员;2:抄送人员;
                    $cc_check_res = OAApproverConfig::where('approval_model_id', $id)
                            ->where('user_type', 2)
                            ->select('id')
                            ->first();
                    if($cc_check_res){      //存在才更新
                        $update_data = [
                            'status' => 2,
                            'updated_at' => Common::num2DateTime(time()),
                            'updated_by' => $user_id,
                        ];
                        $update_res = OAApproverConfig::where('approval_model_id', $id)
                                ->where('user_type', 2)
                                ->update($update_data);
                        if(!$update_res){
                            DB::rollBack();
                            $response = Lang::get('oa_error.approval_update_args_error_221019');
                            break;
                        }    
                    }
                }
                if(!empty($copy_user_id_arr)){
                    $insert_data_copy_user = [];      //审批模型的抄送人员添加数据
                    foreach ($copy_user_id_arr as $k => $v) {
                        $temp = [
                            'approval_model_id' => $approval_model_id,
                            'type' => 1,    //类型 1:用户;2:角色;
                            'user_type' => 2,   //用户类型 1:审批人员;2:抄送人员;
                            'user_id' => $v,
                            'status' => 1,
                            'created_by' => $user_id,
                            'created_at' => Common::num2DateTime(time()),
                        ];
                        $insert_data_copy_user[] = $temp;
                    }
                    $ins_copy_user = OAApproverConfig::insert($insert_data_copy_user);
                    if(!$ins_copy_user){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_args_error_221013');
                        break;
                    }
                }
                //添加 审批模型的抄送人员 end……
                
                //添加审批人、审批条件 start……
                if(!$use_tag){   //未被使用 审批模型的审批人先删除再创建
                    $update_data = [
                        'status' => 2,
                        'updated_at' => Common::num2DateTime(time()),
                        'updated_by' => $user_id,
                    ];
                   //user_type  用户类型 1:审批人员;2:抄送人员;
                    $update_res = OAApproverConfig::where('approval_model_id', $id)
                            ->where('user_type', 1)
                            ->update($update_data);
                    if(!$update_res){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_update_args_error_221020');
                        break;
                    }
                    
                    //审批条件分组
                    $update_res_2 = OAApproverRuleGroup::where('approval_model_id', $id)
                            ->update($update_data);
                    if(!$update_res_2){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_update_args_error_221021');
                        break;
                    }
                    
                    //审批条件
                    $res_check_approval_rule = OAApproverRule::where('approval_model_id', $id)
                            ->where('status', 1)
                            ->select('id')
                            ->first();
                    if($res_check_approval_rule){
                        //存在条件时 才更改删除状态
                        $update_res_3 = OAApproverRule::where('approval_model_id', $id)
                                ->update($update_data);
                        if(!$update_res_3){
                            DB::rollBack();
                            $response = Lang::get('oa_error.approval_update_args_error_221021');
                            break;
                        }    
                    }
                    
                }
                
                $res_insert_approver = OAApproverRuleGroup::addApprover($approval_model_id, $user_id, $approver_arr, 0);
                if(!$res_insert_approver){
                    DB::rollBack();
                    $response = Lang::get('oa_error.approval_args_error_221010');
                    break;
                }
                //添加审批人、审批条件 end……
                
                if($use_tag){
                    //变更原模板 状态
                    $oldApprovalModel->status = 4;
                    $oldApprovalModel->updated_at = Common::num2DateTime(time());
                    $oldApprovalModel->updated_by = $user_id;
                    $res_old = $oldApprovalModel->save();
                    //记录审批模板变更日志
                    $insert_change_log_data = [
                        'old_approval_model_id' => $oldApprovalModel->id, 
                        'old_name' => $oldApprovalModel->name, 
                        'new_approval_model_id' => $approvalModel->id, 
                        'new_name' => $approvalModel->name,
                        'desc' => '审批模板状态变更',
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $res_change_log = OAApprovalModelChangeLog::insert($insert_change_log_data);
                    if(!$res_change_log || !$res_old){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_model_change_log_error_221023');
                        break;
                    }
                }
                
                DB::commit();
            } catch (\Exception $e){
                DB::rollback();
                Log::error('error', ['system' => 'oa', 'event' => 'approval/approvalModelModify', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_model_update_error_221022');
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalModelModify', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-27 上午9:37
     * @Description: 获取审批模型详情
     * @param string $token         用户token
     * @param int $id 审批模型id
     * @link: http://api.anhui.com/oa/approval/approvalModelDetails?token=b6a92158c775fc80e6e3f5d438bf4811&id=2
     * @return  string
     */
    public function approvalModelDetails(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            $id                         = Input::get('id');                         //审批模板id
            
            $approval_model_info = OAApprovalModel::getApprovalModelInfoById($id);
            if(!$approval_model_info){
                $response = Lang::get('oa_error.approval_model_id_error_221024');
                break;
            }
            //$approval_model_info->form_set = json_decode($approval_model_info->form_set, TRUE); //表单数据转换格式
            $form_set_arr = json_decode($approval_model_info->form_set, TRUE); //表单数据转换格式
            $temp_form_set_arr = [];
            if(!empty($form_set_arr)){
                foreach ($form_set_arr as $k => $v) {
                    if(!empty($v['widget_option'])){
                        $v['widget_option'] = explode(',', $v['widget_option']);
                    }
                    $temp_form_set_arr[$k] = $v;
                }
            }
            $approval_model_info->form_set = $temp_form_set_arr;
            //获取审批编号规则信息
            $approval_number_rule_info = OAApprovalNumberRuleConfig::getNumberRuleInfoByApprovalModelId($id);
            if(empty($approval_number_rule_info)){
                $response = Lang::get('oa_error.apply_number_get_error_221044');
                break;
            }
            //获取使用范围
            $apply_config_info = OAApprovalModelApplyConfig::getApprovalModelApplyConfigByApprovalModelId($id);
            if(empty($apply_config_info)){
                $response = Lang::get('oa_error.approval_model_use_get_error_221045');
                break;
            }
            
            //获取抄送人员
            $copy_people_info = OAApproverConfig::getCopyPeopleByApprovalModelId($id);
            if(!empty($copy_people_info)){
                $hrm_user_id_arr = [];  //hrm用户id数组
                foreach ($copy_people_info as $k => $v) {
                    $hrm_user_id_arr[] = $v['hrm_user_id'];
                }
                $hrm_info = HrmUser::getHrmUserInfoByHrmUserid($hrm_user_id_arr);
                if(!empty($hrm_info)){
                    foreach ($copy_people_info as $k => &$v) {
                        $v['hrm_info'] = isset($hrm_info[$v['hrm_user_id']]) ? $hrm_info[$v['hrm_user_id']] : [];
                    }    
                }
            }
            
            //获取各级审批人员、审批条件
            $approver_level = OAApproverRuleGroup::getRuleGroupByApprovalModelId($id);
            if(empty($approver_level)){
                $response = Lang::get('oa_error.approval_model_approver_get_error_221046');
                break;
            }
            
            $result = [
                'approval_model_info' => $approval_model_info,
                'approval_number_rule_info' => $approval_number_rule_info,
                'apply_config_info' => $apply_config_info,
                'copy_people_info' => $copy_people_info,
                'approver_level' => $approver_level,
            ];
            $response = array('code' => 0, 'msg' => 'ok','result' => $result);
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/approvalModelDetails', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-30 下午2:36
     * @Description: OA上传附件
     * @param string $token             用户token
     * @param file $file                附件
     * @param int $file_type            文件类型 (1:图片;2:非图片;)
     * @link: http://api.anhui.com/oa/approval/uploadFile?token=b6a92158c775fc80e6e3f5d438bf4811
     * @return  string
     */
    public function uploadFile(){
        header('Access-Control-Allow-Origin:*');
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'file'=> 'required',   //最大上传2M
                'file_type'=> 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            
            $user_id        = $oa_user->id;                 //管理员id
            //$name           = Input::get('name');           //上传传文件名称
            $upload_file    = Input::file('file');          //上传文件
            $file_type      = Input::get('file_type');      //文件类型 (1:图片;2:非图片;)
            if($upload_file->isValid()){
                //文件上传成功
                $name = $upload_file->getClientOriginalName();  //文件原名称
                //$extension = $upload_file->getClientOriginalExtension(); //扩展名
                $storage_name = date('Ymdhis', time()).'_'.$user_id.'_'.$name;               //存储名称
                $upload_file->move(Config::get('config.oa_apply_files'), $storage_name);
            } else {
                $response = Lang::get('oa_error.apply_file_error_221026');
                $response['result'] = $validator->messages()->all();
                break;
            }
            $file = new OAApplyFiles();
            $file->name = $name;
            $file->storage_name = $storage_name;
            $file->file_type = $file_type;
            $file->status = 1;
            $file->created_at = Common::num2DateTime(time());
            $file->created_by = $user_id;
            try {
                $file->save();
                
            }catch(Exception $e){
                Log::error('error', ['system' => 'oa', 'event' => 'approval/uploadFile', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.apply_file_error_221026');
                break;
            }
            
            $info = [
                'id' => $file->id,
                'name' => $file->name,
                'storage_name' => $file->storage_name,
                'file_type' => $file->file_type,
                'file_url' => Config::get('config.oa_apply_files_url').''.$file->storage_name,
                'created_at' => $file->created_at,
                'created_by' => $file->created_by,
            ];
            $response = array('code' => 0, 'msg' => 'ok','result' => ['info' => $info]);
            try {
                OAOpLog::writeLog('approval/uploadFile', 1, '上传附件', '', json_encode($file), $user_id);
            } catch (Exception $e) {
                Log::error('error', ['system' => 'oa', 'event' => 'approval/uploadFile', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.new_log_write_error_212001');
                break;
            }

        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/uploadFile', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-13 下午3:35
     * @Description: OA删除附件
     * @param string $token             用户token
     * @param int $id                   附件id
     * @link: http://api.anhui.com/oa/approval/deleteFile?token=b6a92158c775fc80e6e3f5d438bf4811&id=1
     * @return  string
     */
    public function deleteFile(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id'=> 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            
            $user_id        = $oa_user->id;                 //管理员id
            $id             = Input::get('id');             //附件id
            
            $file = OAApplyFiles::find($id);
            if(!$file){
                $response = Lang::get('oa_error.apply_file_not_exit_error_221042');
                break;
            }
            $old = clone $file;
            $file->status = 2;
            $file->updated_at = Common::num2DateTime(time());
            $file->updated_by = $user_id;
            try {
                $file->save();
                OAOpLog::writeLog('approval/deleteFile', 3, '删除附件', json_encode($old), json_encode($file), $user_id);
            }catch(Exception $e){
                Log::error('error', ['system' => 'oa', 'event' => 'approval/deleteFile', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.apply_file_delete_error_221043');
                break;
            }
            
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/deleteFile', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-31 上午9:55
     * @Description: 添加申请
     * @param string    $token                          用户token
     * @param int       $approval_model_id              审批模型id
     * @param string    $form_value                     表单的值(json key - value )   多个值用英文逗号分隔 多选框的情况下有可能有多个值
     * $test = [
            'qingjiadeleixing_1' => '年假',
            'tianshu_2' => '2',
            'liyou_3' => '请假的理由',
        ];
     * 例如 {"qingjiadeleixing_1":"\u5e74\u5047","tianshu_2":"2","liyou_3":"\u8bf7\u5047\u7684\u7406\u7531"}
     * @param int       $pc                             pc端消息展示状态(1:显示;2:不显示;)
     * @param int       $wechat                         微站端消息展示状态(1:显示;2:不显示;)
     * @param int       $email                          emali消息通知状态(1:通知;2:不通知;)
     * @param string    $copy_user_id                   抄送人员  json 串 [1,2,3]  htm用户id数组
     * 规则说明
     *      htm用户id数组json串
     * 例如     [1,2,3]
     * @link: http://api.anhui.com/oa/approval/applyAdd?token=b6a92158c775fc80e6e3f5d438bf4811&approval_model_id=1&form_value={"qingjiadeleixing_1":"\u5e74\u5047","tianshu_2":"3","liyou_3":"\u8bf7\u5047\u7684\u7406\u7531"}&pc=1&copy_user_id=[6,7]
     */
    public function applyAdd(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'approval_model_id' => 'required',
                'form_value' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            $approval_model_id          = Input::get('approval_model_id');          //审批模型id
            $form_value                 = Input::get('form_value');                 //表单的值(json key - value )   多个值用英文逗号分隔 多选框的情况下有可能有多个值
            $pc                         = Input::get('pc', 1);                      //pc端消息展示状态(1:显示;2:不显示;)
            $wechat                     = Input::get('wechat', 0);                  //微站端消息展示状态(1:显示;2:不显示;)
            $email                      = Input::get('email', 0);                   //emali消息通知状态(1:通知;2:不通知;)
            $copy_user_id               = Input::get('copy_user_id', '');           //抄送人员  json 串 [1,2,3]  htm用户id数组

            //申请人自主添加抄送人
            if($copy_user_id != ''){
                $copy_user_id_arr = json_decode($copy_user_id, TRUE);   //抄送人员数组
                if(empty($copy_user_id_arr)){
                    $response = Lang::get('oa_error.approval_args_error_221007');
                    break;
                }
                $copy_user_id_arr = OAUser::getUseridByHrmUserid($copy_user_id_arr);    //hrm用户id转换成OA用户id
            } else {
                $copy_user_id_arr = [];
            }
            //获取审批模型对应的抄送人员信息
            $copy_people_info = OAApproverConfig::getCopyPeopleByApprovalModelId($approval_model_id);
            if(!empty($copy_people_info)){
                foreach ($copy_people_info as $k => $v) {
                    $copy_user_id_arr[] = $v['user_id'];
                }
            }
            $copy_user_id_arr = array_unique($copy_user_id_arr);    //抄送人去重
            
            DB::beginTransaction();
            try{
                $user_info = OAUser::getUserInfo($user_id);     //获取用户信息
                $approval_model_info = OAApprovalModel::getApprovalModelInfoById($approval_model_id);     //获取审批模板信息
                $apply_number_arr = OAApprovalNumberRuleConfig::getApplyNumberByApprovalModelId($approval_model_id);    //获取申请编号
                if(empty($apply_number_arr)){
                    $response = Lang::get('oa_error.apply_number_error_221028');
                    break;
                }
                $apply_number = $apply_number_arr['apply_number'];  //申请编号
                $add_value = $apply_number_arr['add_value'];        //当前增长值
                
                //开始添加申请……
                $apply = new OAApply();
                
                $apply->apply_number = $apply_number;                                       //申请编号
                $apply->approval_model_id = $approval_model_id;                             //审批模板id
                $apply->approval_type_id = $approval_model_info->approval_type_id;          //审批类型id
                $apply->approval_type_name = $approval_model_info->approval_type_name;      //审批类型名称
                $apply->form_value = $form_value;                       //表单的值(json key - value )
                $form_value_arr = json_decode($form_value, TRUE);       //表单的值数组
                $apply->level = 1;                                      //当前审批等级
                $apply->pc = $pc;                                       //pc端消息展示状态(1:显示;2:不显示;)
                if($wechat != ''){
                    $apply->wechat = $wechat;                           //微站端消息展示状态(1:显示;2:不显示;)
                }
                if($email != ''){
                    $apply->email = $email;                             //emali消息通知状态(1:通知;2:不通知;)
                }
                $apply->status = 2;     //状态 (1:未提交;2:审批中;3:同意;4:不同意;5:已撤回;6:已删除;)
                $apply->hrm_department_id = $user_info['hr_department_id'];       //hrm平台 部门id
                $apply->hrm_department = $user_info['hr_department_name'];        //hrm平台 部门名称
                $apply->created_at = Common::num2DateTime(time());
                $apply->created_by = $user_id;

                $res_apply = $apply->save();
                if(!$res_apply){
                    DB::rollBack();
                    $response = Lang::get('oa_error.apply_create_error_221027');
                    break;
                }
                $apply_id = $apply->id;         //申请id
                
                //添加 审批模型的抄送人员 进入审批流转表 start……
                if(!empty($copy_user_id_arr)){
                    $insert_data_copy_user = [];      //审批模型的抄送人员添加数据
                    foreach ($copy_user_id_arr as $k => $v) {
                        $temp = [
                            'apply_id' => $apply_id,
                            'user_type' => 2,   //用户类型(1:审批人员;2:抄送人员;)
                            'user_id' => $v,
                            'pc' => $pc,
                            'wechat' => $wechat,
                            'email' => $email,
                            'created_by' => $user_id,
                            'created_at' => Common::num2DateTime(time()),
                        ];
                        $insert_data_copy_user[] = $temp;
                    }
                    $ins_copy_user = OAApplyFlow::insert($insert_data_copy_user);
                    if(!$ins_copy_user){
                        DB::rollBack();
                        $response = Lang::get('oa_error.approval_args_error_221013');
                        break;
                    }
                }
                //添加 审批模型的抄送人员 进入审批流转表 end……

                //添加 审批模型的审批人员 进入审批流转表 start……
                $notify_status_arr = [
                    'pc' => $pc,
                    'wechat' => $wechat,
                    'email' => $email,
                ];
                $ins_approver_user = OAApproverRuleGroup::addApproverToflowByApprovalModelId($apply_id, $approval_model_id, $user_id, $form_value_arr, $notify_status_arr);
                if(!$ins_approver_user){
                    DB::rollBack();
                    $response = Lang::get('oa_error.apply_approver_error_221030');
                    break;
                }
                //添加 审批模型的审批人员 进入审批流转表 end……
                
                //更新 该模板的审批编号 start……
                //该审批模板的审批编号添加数据
                $insert_data_apply_number = [
                    'apply_id' => $apply_id,
                    'apply_number' => $apply_number,
                    'approval_model_id' => $approval_model_id,
                    'now_add_value' => $add_value,
                    'date' => Common::num2DateTime(time(), 'Y-m-d'),
                    'created_at' => Common::num2DateTime(time()),
                    'created_by' => $user_id,
                ];
                $ins_apply_number = OAApplyNumber::insert($insert_data_apply_number);
                if(!$ins_apply_number){
                    DB::rollBack();
                    $response = Lang::get('oa_error.apply_number_add_error_221029');
                    break;
                }
                //更新 该模板的审批编号 end……
                
                //添加消息  start ……
                // 1、 申请人提交后 为申请人添加消息
                $res_news_apply_people = OANewsNotice::addNewsToApplyPeople($apply_id);
                if(!$res_news_apply_people){
                    DB::rollBack();
                    $response = Lang::get('oa_error.news_notice_apply_people_error_221035');
                    break;
                }
                // 2、 申请人提交后 为抄送人添加消息
                $res_news_cc = OANewsNotice::addNewsToCc($apply_id);
                if(!$res_news_cc){
                    DB::rollBack();
                    $response = Lang::get('oa_error.news_notice_cc_error_221036');
                    break;
                }
                // 3、 申请人提交后 为审批人添加消息
                $res_news_approver = OANewsNotice::addNewsToApprover($apply_id);
                if(!$res_news_approver){
                    DB::rollBack();
                    $response = Lang::get('oa_error.news_notice_approver_error_221037');
                    break;
                }
                //添加消息  end   ……
                
                DB::commit();
                $response = array('code' => 0, 'msg' => 'ok', 'result' => ['apply_id' => $apply_id]);
            } catch (\Exception $e){
                DB::rollback();
                Log::error('error', ['system' => 'oa', 'event' => 'approval/applyAdd', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.apply_create_error_221027');
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/applyAdd', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-2 下午2:29
     * @Description: 添加抄送人
     * @param string    $token                          用户token
     * @param int    $apply_id                          申请id
     * @param string    $copy_user_id                   抄送人员  json 串 [1,2,3]  htm用户id数组
     * 规则说明
     *      htm用户id数组json串
     * 例如     [1,2,3]
     * @link: http://api.anhui.com/oa/approval/addCc?token=b6a92158c775fc80e6e3f5d438bf4811&apply_id=292&copy_user_id=[8,9]
     */
    public function addCc(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'apply_id' => 'required',
                'copy_user_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            $apply_id                   = Input::get('apply_id');                   //申请id
            $copy_user_id               = Input::get('copy_user_id');               //抄送人员  json 串 [1,2,3]  htm用户id数组
            
            $apply_info = OAApply::where('id', $apply_id)->first();
            if(!$apply_info){
                $response = Lang::get('oa_error.apply_id_error_221031');
                break;
            }
            $copy_user_id_arr = json_decode($copy_user_id, TRUE);   //抄送人员数组
            if(empty($copy_user_id_arr)){
                $response = Lang::get('oa_error.approval_args_error_221007');
                break;
            }
            $copy_user_id_arr = OAUser::getUseridByHrmUserid($copy_user_id_arr);    //hrm用户id转换成OA用户id
            //添加 审批模型的抄送人员 进入审批流转表 start……
            if(!empty($copy_user_id_arr)){
                $insert_data_copy_user = [];      //审批模型的抄送人员添加数据
                foreach ($copy_user_id_arr as $k => $v) {
                    $temp = [
                        'apply_id' => $apply_info->id,
                        'user_type' => 2,   //用户类型(1:审批人员;2:抄送人员;)
                        'user_id' => $v,
                        'pc' => $apply_info->pc,
                        'wechat' => $apply_info->wechat,
                        'email' => $apply_info->email,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];
                    $insert_data_copy_user[] = $temp;
                }
                $ins_copy_user = OAApplyFlow::insert($insert_data_copy_user);
                if(!$ins_copy_user){
                    $response = Lang::get('oa_error.approval_args_error_221013');
                    break;
                }
            }else{
                $response = Lang::get('oa_error.approval_args_error_221013');
                break;
            }
            //添加 审批模型的抄送人员 进入审批流转表 end……
            
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/addCc', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-2 下午4:20
     * @Description: 转发审批人
     * @param string    $token                          用户token
     * @param int    $apply_id                          申请id
     * @param int    $approver_user_id                 审批人员id
     * @link: http://api.anhui.com/oa/approval/transferApproval?token=b6a92158c775fc80e6e3f5d438bf4811&apply_id=292&approver_user_id=8
     */
    public function transferApproval(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'apply_id' => 'required',
                'approver_user_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            $apply_id                   = Input::get('apply_id');                   //申请编号
            $approver_user_id           = Input::get('approver_user_id');           //审批人员id
            OAOpLog::writeLog('approval/transferApproval', 2, '转发审批人', '', $approver_user_id, $user_id);
            $apply_info = OAApply::where('id', $apply_id)->first();
            if(!$apply_info){
                $response = Lang::get('oa_error.apply_id_error_221031');
                break;
            }
            //查询该审批人的流转信息
            $select_arr = [
                'id', 'apply_id', 'user_type', 'user_id', 'level', 'approval_way', 'op_type', 'postil', 
                'status', 'pc', 'wechat', 'email',
            ];
            $flow_info = OAApplyFlow::where('apply_id', $apply_id)
                    ->where('user_id', $user_id)
                    ->where('user_type', 1)
                    ->select($select_arr)
                    ->first();
            if(!$flow_info){
                $response = Lang::get('oa_error.apply_transfer_error_221032');
                break;
            }
            
            $approver_user_info = OAUser::getUserByHrmUserid([$approver_user_id]);    //hrm用户id获取成OA用户信息
            $to_user_info = $approver_user_info[$approver_user_id];     //转批接收人信息
            DB::beginTransaction();
            try{
                //更新原审批人的流转信息 start ……
                $update_data = [
                    'status' => 5,  //状态(1:未审批;2:已审批;3:他人已审批;4:申请人已撤回;5:审批人已转发;6:已删除;)
                    'updated_at' => Common::num2DateTime(time()),
                    'updated_by' => $user_id,
                ];
                $update_res = OAApplyFlow::where('id', $flow_info->id)->update($update_data);
                if(!$update_res){
                    DB::rollback();
                    $response = Lang::get('oa_error.apply_flow_update_error_221033');
                    break;
                }
                //更新原审批人的流转信息 end ……

                //添加新的审批人信息 到 流转表 start ……
                if(!empty($to_user_info)){
                    $insert_data_user = [
                        'apply_id' => $apply_info->id,
                        'user_type' => 3,   //用户类型(1:审批人员;2:抄送人员;3:转批接收人;)
                        'user_id' => $to_user_info['id'],
                        'level' => $flow_info->level,
                        'status' => 1,
                        'approval_way' => $flow_info->approval_way,
                        'pc' => $apply_info->pc,
                        'wechat' => $apply_info->wechat,
                        'email' => $apply_info->email,
                        'created_by' => $user_id,
                        'created_at' => Common::num2DateTime(time()),
                    ];

                    $ins_user = OAApplyFlow::insert($insert_data_user);
                    if(!$ins_user){
                        DB::rollback();
                        $response = Lang::get('oa_error.transfer_add_error_221034');
                        break;
                    }
                    //添加消息  start ……
                    // 暂时注释 18-8-23 上午10:15
//                    $res_news_transfer = OANewsNotice::addNewsToTransferApprover($apply_id, $user_id, $to_user_info['id']);
//                    if(!$res_news_transfer){
//                        DB::rollBack();
//                        $response = Lang::get('oa_error.news_notice_cc_error_221047');
//                        break;
//                    }
                    //添加消息  end   ……
                }else{
                    DB::rollback();
                    $response = Lang::get('oa_error.transfer_add_error_221034');
                    break;
                }
                //添加新的审批人信息 到 流转表 end ……
                
                DB::commit();
            } catch (\Exception $e){
                DB::rollback();
                Log::error('error', ['system' => 'oa', 'event' => 'approval/transferApproval', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.transfer_add_error_221034');
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/transferApproval', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-6 下午2:39
     * @Description: 申请人撤回申请
     * @param string    $token                          用户token
     * @param int    $apply_id                          申请id
     * @link: http://api.anhui.com/oa/approval/applyCancel?token=b6a92158c775fc80e6e3f5d438bf4811&apply_id=292
     */
    public function applyCancel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'apply_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            $apply_id                   = Input::get('apply_id');                   //申请编号
            
            $apply_info = OAApply::where('id', $apply_id)->first();
            if(!$apply_info){
                $response = Lang::get('oa_error.apply_id_error_221031');
                break;
            }

            DB::beginTransaction();
            try{
                //更新申请表中状态 start ……
                $update_data = [
                    'status' => 5,  //状态 (1:未提交;2:审批中;3:同意;4:不同意;5:已撤回;6:已删除;)
                    'updated_at' => Common::num2DateTime(time()),
                    'updated_by' => $user_id,
                ];
                $update_res = OAApply::where('id', $apply_id)->update($update_data);
                if(!$update_res){
                    DB::rollback();
                    $response = Lang::get('oa_error.apply_status_error_221038');
                    break;
                }
                //更新申请表中状态 end ……
                
                //更新审批人的流转信息 start ……
                $update_data = [
                    'status' => 4,  //状态(1:未审批;2:已审批;3:他人已审批;4:申请人已撤回;5:审批人已转发;6:已删除;)
                    'updated_at' => Common::num2DateTime(time()),
                    'updated_by' => $user_id,
                ];
                $update_res = OAApplyFlow::where('apply_id', $apply_id)
                        ->whereIn('user_type', [1, 3])
                        ->where('status', 1)
                        ->update($update_data);
                if(!$update_res){
                    DB::rollback();
                    $response = Lang::get('oa_error.apply_flow_update_error_221033');
                    break;
                }
                //更新审批人的流转信息 end ……
                
                //添加消息  start ……
                // 为抄送人添加消息
                $res_news_cc = OANewsNotice::addNewsToCc($apply_id, 5, $user_id);
                if(!$res_news_cc){
                    DB::rollBack();
                    $response = Lang::get('oa_error.news_notice_cc_error_221036');
                    break;
                }
                // 为审批人添加消息
                $res_news_approver = OANewsNotice::addNewsToApprover($apply_id, 5, $user_id);
                if(!$res_news_approver){
                    DB::rollBack();
                    $response = Lang::get('oa_error.news_notice_approver_error_221037');
                    break;
                }
                //添加消息  end   ……
                
                DB::commit();
            } catch (\Exception $e){
                DB::rollback();
                Log::error('error', ['system' => 'oa', 'event' => 'approval/applyCancel', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.apply_cancel_error_221039');
                break;
            }
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/applyCancel', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-8-7 上午9:52
     * @Description: 申请删除 (对自己不展示)    允许删除的状态有 申请同意、不同意、撤回
     * @param string    $token                          用户token
     * @param int    $apply_id                          申请id
     * @link: http://api.anhui.com/oa/approval/applyDelete?token=b6a92158c775fc80e6e3f5d438bf4811&apply_id=292
     */
    public function applyDelete(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'apply_id' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id                    = $oa_user->id;                             //管理员id
            $apply_id                   = Input::get('apply_id');                   //申请编号
            
            $apply_info = OAApply::where('id', $apply_id)->first();
            if(!$apply_info){
                $response = Lang::get('oa_error.apply_id_error_221031');
                break;
            }
            if(!in_array($apply_info->status, OAApply::$canDeleteStatusArr)){
                $response = Lang::get('oa_error.apply_delete_status_error_221040');
                break;
            }
            
            //更新申请表中状态 start ……
            $update_data = [
                'status' => 6,  //状态(1:未审批;2:已审批;3:他人已审批;4:申请人已撤回;5:审批人已转发;6:已删除;)
                'updated_at' => Common::num2DateTime(time()),
                'updated_by' => $user_id,
            ];
            $update_res = OAApply::where('id', $apply_id)->update($update_data);
            if(!$update_res){
                $response = Lang::get('oa_error.apply_delete_error_221041');
                break;
            }
            //更新申请表中状态 end ……
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'approval/applyDelete', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    
}